package com.goldsprite.microhorigame.screens.tests;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.goldsprite.gameframeworks.assets.GameRes;
import com.goldsprite.gameframeworks.ecs.SpriteUtils;
import com.goldsprite.gameframeworks.input.GameInputSystem;
import com.goldsprite.microhorigame.screens.basics.ExampleGScreen;
import com.goldsprite.microhorigame.screens.games.CameraTool;

public class TextureWrapTest extends ExampleGScreen {
	private GameRes res = GameRes.Background_Forest;
	private String skyPath = "sprites/backs/forest/forest_sky.png";
	private TextureRegion skyRegion, blackRectRegion;
	private OrthographicCamera worldCam;
	private SpriteBatch batch;
	private Vector2 moveDir;
	private float[] currentZoom = new float[]{1f};

	// 相机移动速度
	private float cameraMoveSpeed = 300f;
	private Stage stage;

	// 纹理缩放相关变量
	private float textureScale = 1f;
	private final float textureScaleSpeed = 1f;
	private final float minTextureScale = 0.1f;
	private final float maxTextureScale = 5f;
	private float baseTextureWidth, baseTextureHeight; // 基础纹理尺寸

	@Override
	public void create() {
		// 初始化世界相机
		worldCam = new OrthographicCamera();
		worldCam.setToOrtho(false, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());

		stage = new Stage(getViewport());

		// 初始化渲染批次
		batch = new SpriteBatch();

		// 加载天空纹理
		skyRegion = new TextureRegion(new Texture(Gdx.files.internal(skyPath)));
		blackRectRegion = new TextureRegion((Texture) GameRes.Monster_Door.getResource());

		// 设置Wrap模式
		skyRegion.getTexture().setWrap(Texture.TextureWrap.Repeat, Texture.TextureWrap.ClampToEdge);

		// 保存基础纹理尺寸
		baseTextureWidth = skyRegion.getTexture().getWidth();
		baseTextureHeight = skyRegion.getTexture().getHeight();

		// 获取输入系统
		moveDir = GameInputSystem.getInstance().getInputAction("Move").readValue();

		// 添加相机缩放事件处理器
		getImp().addProcessor(CameraTool.createCamZoomEvent(worldCam, stage, currentZoom));
	}

	@Override
	public void render0(float delta) {
		// 处理相机移动
		handleCameraMovement(delta);

		// 处理相机缩放
		handleCameraZoom();

		// 处理纹理缩放
		handleTextureScale(delta);

		// 更新相机
		worldCam.update();
		batch.setProjectionMatrix(worldCam.combined);

		// 开始渲染
		batch.begin();

		// 渲染无限平铺的天空
		{
			// 计算绘制大小（同步纹理缩放）
			float drawWidth = baseTextureWidth * textureScale;
			float drawHeight = baseTextureHeight * textureScale;

			// 计算绘制位置（屏幕中心对齐）
			float centerX = getViewCenter().x;
			float centerY = getViewCenter().y;
			float x = centerX - drawWidth / 2f;
			float y = centerY - drawHeight / 2f;

			// 绘制纹理（从中心向四周延伸）
			batch.draw(skyRegion, x, y, drawWidth, drawHeight);

			// 绘制参考矩形
			batch.draw(blackRectRegion, centerX-50, centerY - 100, 100, 200);
		}

		batch.end();
	}

	/**
	 * 处理纹理缩放 (Q缩小, E放大)
	 */
	private void handleTextureScale(float delta) {
		if (Gdx.input.isKeyPressed(com.badlogic.gdx.Input.Keys.Q)) {
			textureScale = Math.max(minTextureScale, textureScale - textureScaleSpeed * delta);
			updateTextureRegion();
		}
		if (Gdx.input.isKeyPressed(com.badlogic.gdx.Input.Keys.E)) {
			textureScale = Math.min(maxTextureScale, textureScale + textureScaleSpeed * delta);
			updateTextureRegion();
		}
	}

	/**
	 * 更新纹理区域大小（从中心向四周延伸）
	 */
	private void updateTextureRegion() {
		// 根据缩放比例计算新的纹理区域
		int scaledWidth = (int)(baseTextureWidth * textureScale);
		int scaledHeight = (int)(baseTextureHeight * textureScale);

		// 计算UV偏移，确保从中心向四周延伸
		int offsetX = (scaledWidth - (int)baseTextureWidth) / 2;
		int offsetY = (scaledHeight - (int)baseTextureHeight) / 2;

		// 更新纹理区域（从中心向四周延伸）
		skyRegion.setRegion(
			-offsetX,
			-offsetY,
			scaledWidth,
			scaledHeight
		);
	}

	/**
	 * 处理WASD相机移动
	 */
	private void handleCameraMovement(float delta) {
		// 标准化移动向量
		if (moveDir.x != 0 || moveDir.y != 0) {
			Vector2 moveVector = moveDir.nor();
			worldCam.position.x -= moveVector.x * cameraMoveSpeed * delta;
			worldCam.position.y -= moveVector.y * cameraMoveSpeed * delta;
		}
	}

	/**
	 * 处理相机缩放
	 */
	private void handleCameraZoom() {
		if (currentZoom[0] != worldCam.zoom) {
			worldCam.zoom = Math.max(0.1f, currentZoom[0]);
			worldCam.update();
		}
	}

	@Override
	public void resize(int width, int height) {
		super.resize(width, height);
	}

	@Override
	public String getIntroduction() {
		return "纹理平铺测试场景\n\n" +
			"功能说明：\n" +
			"• 天空纹理左右上下无限平铺\n" +
			"• 纹理从中心向四周延伸缩放\n" +
			"• 初始大小为1/2屏幕\n" +
			"• Q键：缩小纹理\n" +
			"• E键：放大纹理\n" +
			"• WASD/方向键：移动相机\n" +
			"• 鼠标滚轮：缩放相机\n" +
			"• 双指手势（触摸屏）：缩放相机\n\n" +
			"测试目的：\n" +
			"验证无限平铺纹理的渲染效果和相机控制功能";
	}
}
